<template>
  <div class="hour-compare-container">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>时数据比对</span>
        </div>
      </template>
      
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="广告位" required>
          <el-select v-model="searchForm.adspaceId" placeholder="请选择广告位" clearable filterable>
            <el-option
              v-for="space in spaceOptions"
              :key="space.id"
              :label="space.name"
              :value="space.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        
        <el-form-item label="指标" required>
          <el-select v-model="searchForm.metric" placeholder="请选择指标" clearable style="width: 200px;">
            <el-option label="请求数" value="requests" />
            <el-option label="点击数" value="clicks" />
            <el-option label="展示数" value="imps" />
            <el-option label="错误数" value="errors" />
            <el-option label="失败数" value="fails" />
            <el-option label="填充数" value="forwards" />
            <el-option label="限制数" value="limits" />
            <el-option label="超时数" value="timeouts" />
            <el-option label="获胜数" value="wins" />
            <el-option label="低价数" value="lowPrices" />
            <el-option label="无广告数" value="noAds" />
            <el-option label="媒体出价" value="prices" />
            <el-option label="DSP出价" value="rprices" />
            <el-option label="成本" value="iprices" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="dt" label="日期" width="120" fixed />
        <el-table-column v-for="hour in hours" :key="hour" :prop="`hour${hour}`" :label="`${hour}`" width="120" align="center">
          <template #default="{ row }">
            {{ row[`hour${hour}`] || 0 }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { fetchHourCompareData } from '@/api/report'
import { fetchSpaceData, type ApiSpaceItem } from '@/api/space'

interface SearchForm {
  adspaceId: string
  startDt: string
  endDt: string
  metric: string
}

interface HourCompareData {
  adspaceId: string
  [key: string]: any // 动态的小时字段
}

interface SpaceOption {
  id: string
  name: string
}

// 搜索表单
const searchForm = reactive<SearchForm>({
  adspaceId: '',
  startDt: '',
  endDt: '',
  metric: ''
})

// 日期范围
const dateRange = ref<string[]>([])

// 表格数据
const tableData = ref<HourCompareData[]>([])

// 加载状态
const loading = ref(false)

// 广告位选项
const spaceOptions = ref<SpaceOption[]>([])

// 小时列表（00-23）
const hours = Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0'))

// 加载广告位选项数据
const loadSpaceOptions = async () => {
  try {
    const params = {
      current: 1,
      size: 1000 // 获取所有广告位数据
    }
    
    const response = await fetchSpaceData(params)
    spaceOptions.value = response.records.map(item => ({
      id: item.id || '',
      name: item.name || ''
    }))
  } catch (error) {
    console.error('加载广告位选项失败:', error)
  }
}

// 查询处理
const handleSearch = async () => {
  if (!searchForm.adspaceId) {
    ElMessage.warning('请选择广告位')
    return
  }
  
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }
  
  if (!searchForm.metric) {
    ElMessage.warning('请选择指标')
    return
  }
  
  // 将日期范围数据映射到搜索表单
  searchForm.startDt = dateRange.value[0]
  searchForm.endDt = dateRange.value[1]
  
  loading.value = true
  try {
    // 调用接口获取数据
    const response = await fetchHourCompareData({
      adspaceId: searchForm.adspaceId,
      startDt: searchForm.startDt,
      endDt: searchForm.endDt,
      metric: searchForm.metric
    })
    
    // 处理返回数据 - 按照日期进行分组，按小时匹配指标
    if (response) {
      // 按日期分组
      const groupedByDate: Record<string, any> = {}
      
      response.forEach((item: any) => {

        if (!item.dt) return
        // 预处理一些数据
        if(searchForm.metric === 'iprices'){
          item.iprices = (item.iprices/100000).toFixed(2) + '元'|| 0 + '元'
        }
        
        if (!groupedByDate[item.dt]) {
          groupedByDate[item.dt] = {
            adspaceId: item.adspaceId,
            dt: item.dt
          }
          
          // 初始化所有小时字段为0
          hours.forEach(hour => {
            groupedByDate[item.dt][`hour${hour}`] = 0
          })
        }
        
        // 按小时匹配指标数据
        if (item.hour && searchForm.metric) {
          const hourKey = `hour${item.hour.padStart(2, '0')}`
          const metricValue = item[searchForm.metric] || 0
          groupedByDate[item.dt][hourKey] = metricValue
        }
      })
      
      // 转换为数组格式
      tableData.value = Object.values(groupedByDate)
    } else {
      tableData.value = []
    }
  } catch (error) {
    console.error('查询时数据比对失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const handleReset = () => {
  searchForm.adspaceId = ''
  searchForm.startDt = ''
  searchForm.endDt = ''
  searchForm.metric = ''
  dateRange.value = []
  tableData.value = []
}

onMounted(async () => {
  // 加载广告位选项数据
  await loadSpaceOptions()
})
</script>

<style scoped>
.hour-compare-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form-item {
  margin-bottom: 0;
}
</style>